# -*- coding: utf-8 -*-
# filename: nbiot_server.py

import socket
from time import ctime
from handle import getResetFlag, setResetFlag, MAX_LOG_NUM

def nbiot_server(fn='./nbiot_server.txt'):
    address = ('219.222.189.166', 8042)
    # address = ('127.0.0.1', 8042)
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.bind(address)
    recvCnt = 0
    with open(fn, 'wb') as fs:  # 保证启动时存在此文件，覆盖已存在的文件
        # fs.write(ctime())
        pass
    while True:
        data, addr = s.recvfrom(2048)
        if getResetFlag():
            recvCnt = 0
            setResetFlag(False)
        rst = "[{cnt}]&lt;{time}&gt;{data}{addr}<br/>\n"\
            .format(cnt=recvCnt+1, time=ctime()[4:], data=data, addr=addr) # HTML字符实体转义
        # print rst
        # s.sendto(data, addr)
        try:
            if recvCnt%MAX_LOG_NUM == 0:
                with open(fn, 'wb') as fs:  # 覆盖已存在的文件
                    fs.write(rst)
            else:
                with open(fn, 'ab') as fs:  # 在已存在的文件里追加
                    fs.write(rst)
        except Exception, err:
            print err
            break
        recvCnt += 1
    s.close()

if __name__ == '__main__':
    nbiot_server()
